<?php
namespace app\api\controller\xilumarket;


use app\common\controller\Api;
use app\common\model\xilumarket\TopicAd;
use app\common\model\xilumarket\TopicUser;
use app\common\model\xilumarket\UserFocus;
use app\common\model\xilumarket\TopicBanUser;
use app\common\model\xilumarket\Topic AS TopicModel;

class Topic extends Api
{
    protected $noNeedLogin = ['top_lists','lists','invitation','topic_users'];
    protected $noNeedRight = ['*'];
    /**
     * 推荐列表
     */
    public function top_lists(){
        $pagesize = $this->request->param('pagesize',4);
        $this->success('查询成功',TopicModel::topLists($pagesize));
    }

    /**
     * 查询用户在话题中的身份
     *
     * @return void
     */
    public function whoami() {
        $topId = $this->request->param('topic_id');
        if(!$topId) {
            $this->error('请指定话题');
        }
        $topic = TopicUser::where(['topic_id' => $topId, 'user_id' => $this->auth->id])->find();
        $this->success('查询成功',$topic);
    }

    /**
     * 禁言贴吧用户
     *
     * @return void
     */
    public function ban() {
        $topicId = input('topic_id');
        if(!$topicId) {
            $this->error('请指定话题');
        }
        $uid = input('user_id');
        if(!$uid) {
            $this->error('请指定用户');
        }
        $topicUser = TopicUser::where(['topic_id' => $topicId, 'user_id' => $this->auth->id])->find();
        if(!$topicUser->checkAdmin()){
            $this->error('您没有权限');
        }
        $banTUser=$topicUser->checkUser($uid);
        if(!$banTUser) {
            $this->error('当前用户不存在该话题');
        }
        if($banTUser->is_admin > 0) {
            $this->error('当前用户是管理员无法被禁言');
        }
        $banUser = TopicBanUser::where([
            'topic_id' => $topicId,
            'user_id' => $uid,
            'expir_time' => ['>', time()]
        ])->find();
        if($banUser) {
            $this->error('当前用户已被禁言');
        }
        $banUser = TopicBanUser::create([
            'topic_user_id' => $banTUser->id,
            'topic_id' => $topicId,
            'user_id' => $uid,
            'expir_time' => strtotime(input('expir_time')),
            'createtime' => time(),
            'create_by' =>$this->auth->id
        ]);
        $this->success('禁言成功', $banUser);
    }

    /**
     * 解除禁言
     *
     * @return void
     */
    public function unban() {
        $topicId = input('topic_id');
        if(!$topicId) {
            $this->error('请指定话题');
        }
        $uid = input('user_id');
        if(!$uid) {
            $this->error('请指定用户');
        }
        $topicUser = TopicUser::where(['topic_id' => $topicId, 'user_id' => $this->auth->id])->find();
        if(!$topicUser->checkAdmin()){
            $this->error('您没有权限');
        }
        $banUser = TopicBanUser::where([
            'topic_id' => $topicId,
            'user_id' => $uid,
            'expir_time' => ['>', time()]
        ])->find();
        if($banUser) {
            $banUser->save(['deletetime' => time(), 'delete_by' => $this->auth->id]);
        }
        $this->success('解禁成功', $banUser);
    }

    /**
     * 话题列表
     */
    public function lists(){
        $params = $this->request->param('');
        $this->success('查询成功',TopicModel::lists($params,$this->auth->id));
    }

    /**
     * 话题圈
     */
    public function invitation(){
        #圈子
        $topic_id = $this->request->param('topic_id');
        if(!$topic_id){
            $this->error('参数错误');
        }
        $row = TopicModel::field('id,name,description,image,forum_count,province_id,city_id,region_id')
            ->where('status','normal')
            ->where('id',$topic_id)
            ->find();
        $row && $row->setAttr('forumuser_count',$row->getTopicUserCount());
        $row && $row->setAttr('topic_join_count',$row->getTopicJoinUserCount());
        $row && $row->setAttr('topic_users',TopicUser::getUsers($topic_id,5));
        $row && $row->setAttr('is_join',$this->auth->isLogin()?TopicUser::isJoinTopic($topic_id,$this->auth->id):false);
        $this->success('查询成功',$row);
    }

    /**
     * 设置管理员
     *
     * @param int $topicId
     * @return void
     */
    public function set_admin() {
        $topicId = input('topic_id');
        $user = $this->auth->id;
        $user_id = input('user_id');
        $tuser = TopicUser::where(['user_id' => $user, 'topic_id' => $topicId, 'is_admin' => 11])->find();
        if(!$tuser) {
            $this->error('仅吧主可以设置管理员');
        }
        $res = TopicUser::where(['user_id' => $user_id, 'topic_id' => $topicId])->update(['is_admin' => 10]);
        if($res){
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }
    }

    /**
     * 设置管理员
     *
     * @param int $topicId
     * @return void
     */
    public function unset_admin() {
        $topicId = input('topic_id');
        $user = $this->auth->id;
        $user_id = input('user_id');
        $tuser = TopicUser::where(['user_id' => $user, 'topic_id' => $topicId, 'is_admin' => 11])->find();
        if(!$tuser) {
            $this->error('仅吧主可以解除管理员');
        }
        $res = TopicUser::where(['user_id' => $user_id, 'topic_id' => $topicId])->update(['is_admin' => '00']);
        if($res){
            $this->success('解除成功');
        }else{
            $this->error('解除失败');
        }
    }

    /**
     * @ApiTitile (加入&取消加入)
     * @ApiSummary (加入&取消加入)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilumarket.topic/toggle_join)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=topic_id, type=int, require=true, description="id")
     */
    public function toggle_join() {
        $topic_id = $this->request->post('topic_id');
        $result = TopicUser::toggleJoin($this->auth->id, $topic_id);
        $this->success('操作成功',["is_join"=>$result?true:false]);
    }
    
    /**
     * 全部圈友
     */
    public function topic_users(){
        $topic_id = $this->request->param('topic_id');
        $pagesize = $this->request->param('pagesize',10);
        if(!$topic_id){
            $this->error('参数错误');
        }
        $userId = $this->auth->id;
        $lists = TopicUser::field('id,topic_id,user_id,is_admin')
            ->with(['user'=>function($q){
                $q->withField(['id','nickname','avatar']);
            }, 'ban'=>function($q) {
                $q->where('expir_time', '>', time());
            }])
            ->order('is_admin','desc')
            ->where('topic_id',$topic_id)
            ->paginate($pagesize)
            ->each(function ($row) use($userId){
                $row->setAttr("fans_count",UserFocus::getFocusCount($row->user_id));
                $row->setAttr("is_focus_count",UserFocus::isFocus($userId,$row->user_id));
            });
        $this->success("",$lists);
    }

    /**
     * 修改贴吧信息
     *
     * @param int $id
     * @return void
     */
    public function updateTopic($id) {
        $tuser = TopicUser::where(['user_id' => $this->auth->id, 'topic_id' => $id, 'is_admin' => 11])->find();
        if(!$tuser) {
            $this->error('仅吧主可以修改');
        }
        $post = $this->request->post();
        $params = array_filter($post, function($val, $key) {
            return in_array($key, ['name', 'image', 'description']);
        }, ARRAY_FILTER_USE_BOTH);
        if(!$id) {
            $this->error('请选择要修改的话题');
        }
        $topic = TopicModel::find($id);
        $res = $topic->save($params);
        if($res) {
            $this->success('成功', $topic);
        }
        $this->error('修改失败，请稍后重试');
    }

    public function getTimeRange() {
        $arr = TopicAd::getTimerangeArray();
        $res = [];
        foreach($arr as $key => $val) {
            $res[] = [
                'code' => $key, 
                'title' => $val[0] . '-' . $val[1]
            ];
        }
        $this->success('获取成功', $res);
    }
}